package com.zx.ishopping.interceptors;

import com.zx.ishopping.utils.JwtUtil;
import com.zx.ishopping.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * JWT拦截器
 * @author 祝鑫
 * 时间 2025/6/24
 */

@Slf4j
@Component
public class LoginInterceptors implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request , HttpServletResponse response , Object handler){

      
        
        try {
            String token = request.getHeader("token");
            Map<String, Object> tokenData = JwtUtil.getTokenData(token);
            Long id = ((Number) tokenData.get("id")).longValue();
            ThreadLocalUtil.set(id);
            Object o = ThreadLocalUtil.get();
            
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    /**
     * 请求处理完毕，释放线程资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request , HttpServletResponse response , Object handler , Exception ex){
        ThreadLocalUtil.remove();
    }
}

